package com.knowswift.security.provider;

import com.knowswift.security.AuthUserDetails;
import com.knowswift.security.AuthUserDetailsService;
import com.knowswift.security.log.LoginLogService;
import com.knowswift.security.token.AppleAuthenticationToken;
import lombok.SneakyThrows;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import java.util.Collection;


public class AppleAuthenticationProvider extends AbstractMatchClassAuthenticationProvider {
    private final LoginLogService loginLogService;

    public AppleAuthenticationProvider(AuthUserDetailsService userDetailsService, Class<? extends AppleAuthenticationToken> matchClass, LoginLogService loginLogService) {
        super(userDetailsService, matchClass);
        this.loginLogService = loginLogService;
    }

    @SneakyThrows
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        AppleAuthenticationToken authenticationToken = (AppleAuthenticationToken) authentication;

        String appleId = authenticationToken.getAppleId();

        AuthUserDetails authUserDetails = userDetailsService.loadUserByAppleId(appleId);
        checkAuthUserDetails(authUserDetails);
        return matchClass.getConstructor(Collection.class, AuthUserDetails.class, String.class)
                .newInstance(authUserDetails.getAuthorities(), authUserDetails, appleId);

    }
}
